#include <glog/logging.h>
#include "code_scan.hpp"

// glob_t glob_result;
// if (glob("/dev/ttyACM*", GLOB_ERR, nullptr, &glob_result) != 0 || glob_result.gl_pathc == 0) {
//     std::cerr << "未找到 /dev/ttyACM* 设备" << std::endl;
//     return false;
// }

// device_path = glob_result.gl_pathv[0];
// globfree(&glob_result);

code_scan::code_scan(uart_v2 *uart) : _uart(uart),
                                      _init_flag(YJ_ERROR)
{
    if (!_uart)
    {
        _init_flag = YJ_ERROR;
        LOG(ERROR) << "[code_scan] Error: Invalid UART pointer";
        return;
    }

    if (_uart->uart_open() != YJ_OK)
    {
        _init_flag = YJ_ERROR;
        LOG(ERROR) << "[code_scan] Error: UART open failed";
        return;
    }
    _init_flag = YJ_OK;
}

yj_return code_scan::get_code()
{
    if (_init_flag != YJ_OK)
    {
        LOG(ERROR) << "[code_scan] Not initialized properly";
        return YJ_ERROR;
    }

    // _code.clear();
    std::lock_guard<std::mutex> lock(_uart->uart_get_mutex());

    uint8_t buffer[100] = {0};
    const int max_len = sizeof(buffer) - 1;

    int recv_len = _uart->uart_recv_one_by_one(buffer, max_len, 100);

    if (recv_len <= 0)
    {
        // LOG(WARNING) << "[code_scan] No data received";
        return YJ_ERROR;
    }

    std::lock_guard<std::mutex> lock2(_data_lock);

    _code = std::string((char *)buffer);

    // LOG(INFO) << "[code_scan] Scanned code: " << code;
    return YJ_OK;
}

yj_return code_scan::get_color_index_with_round(uint8_t round_index, uint8_t times_index, uint8_t &color_index)
{
    if (_code.length() < 6)
    {
        LOG(ERROR) << "[code_scan] Code length is too short";
        return YJ_ERROR;
    }

    if (round_index == 1)
        round_index =  round_index + 3;
    color_index = _code[round_index + times_index] - '0';

    return YJ_OK;
}


std::string code_scan::get_code_str()
{
    std::lock_guard<std::mutex> lock(_data_lock);
    if (_code.length() < 6)
    {
        return "---+---";
    }
    return _code;
}